package com.cpi.cornpp.balanceversion.services;

import java.util.Iterator;
import java.util.List;

import com.cpi.cornpp.balanceversion.converter.BalanceVersionConverter;
import com.cpi.cornpp.balanceversion.dao.BalanceVersionDAO;
import com.cpi.cornpp.balanceversion.dto.BalanceVersionDTO;
import com.cpi.cornpp.balanceversion.exception.BalanceVersionException;
import com.cpi.cornpp.balanceversion.view.BalanceVersionView;
import com.cpi.cornpp.common.exception.CornPPException;

/**
 * Balance Version Service
 * @author Edgar Joao
 *
 */
public class BalanceVersionService {
	/**
	 * @author Edgar Joao
	 * @param versionId
	 * @return
	 * @throws BalanceVersionException
	 */
	public List getBalanceVersions(int versionId) throws BalanceVersionException{
		BalanceVersionDAO balanceVersionDAO = null;
		BalanceVersionConverter balanceVersionConverter = null;
		List listOfBalansVersions = null;
		try{
			balanceVersionDAO = new BalanceVersionDAO();
			balanceVersionConverter = new BalanceVersionConverter();
			listOfBalansVersions = balanceVersionConverter.convertDTOsToViews(balanceVersionDAO.getBalansVersions(versionId));										
		} catch (BalanceVersionException balanceVersionException) {
			throw balanceVersionException;
		} catch (Exception e){
			BalanceVersionException balanceVersionException = null;
			e.printStackTrace(System.out);
			balanceVersionException = new BalanceVersionException(e , CornPPException.LAYER_SERVICE,CornPPException.ACTION_LISTS);
			throw balanceVersionException;
		}	
		return listOfBalansVersions;
	}
	/**
	 * @author Edgar Joao
	 * @param balansVersionsList
	 * @throws BalanceVersionException
	 */
	public void updateBalansVersions(List balansVersionsList) throws BalanceVersionException{
		Iterator iterator = null;
		BalanceVersionView balanceVersionView = null;
		BalanceVersionDTO balanceVersionDTO = null;
		BalanceVersionConverter balanceVersionConverter = null;
		BalanceVersionDAO balanceVersionDAO = null;
		try{
			iterator = balansVersionsList.iterator();
			balanceVersionConverter = new BalanceVersionConverter();
			balanceVersionDAO = new BalanceVersionDAO();
			while(iterator.hasNext()){
				balanceVersionView = (BalanceVersionView) iterator.next();
				balanceVersionDTO = balanceVersionConverter.converterBalanceVersionViewToDto(balanceVersionView);
				balanceVersionDAO.updateBalansVersions(balanceVersionDTO);				
			}					
		} catch (BalanceVersionException balanceVersionException) {
			throw balanceVersionException;
		} catch (Exception e){
			BalanceVersionException balanceVersionException = null;
			e.printStackTrace(System.out);
			balanceVersionException = new BalanceVersionException(e , CornPPException.LAYER_SERVICE,CornPPException.ACTION_LISTS);
			throw balanceVersionException;
		}	
		
	}
}
